package cn.com.cym.gamezao.service.grk.impl;

import cn.com.cym.gamezao.base.BaseImpl;
import cn.com.cym.gamezao.base.BaseRepository;
import cn.com.cym.gamezao.base.SearchPage;
import cn.com.cym.gamezao.entity.grk.MedicalHistory;
import cn.com.cym.gamezao.repository.grk.MedicalHistoryRepository;
import cn.com.cym.gamezao.service.grk.MedicalHistoryService;
import cn.com.cym.gamezao.util.CommonUtils;
import cn.hutool.core.util.ReflectUtil;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.lang.reflect.Field;
import java.util.Map;

@AllArgsConstructor
@Service
@Transactional(rollbackFor = Exception.class)
public class MedicalHistoryImpl extends BaseImpl<MedicalHistory> implements MedicalHistoryService {

    final MedicalHistoryRepository thisRepository;

    @Override
    public BaseRepository<MedicalHistory, Long> getJpaRepository() {
        return thisRepository;
    }

    @Override
    public Page<MedicalHistory> findByPageable(SearchPage searchPage) {
        String[] sortBy = searchPage.getSortBy().toArray(new String[searchPage.getSortBy().size()]);

        Pageable pageable = PageRequest.of(searchPage.getCurrent()-1, searchPage.getPageSize(), searchPage.getSort(), sortBy);

        Specification<MedicalHistory> specification = new Specification<>() {

            private static final long serialVersionUID = -2661077778894635593L;

            @SneakyThrows
            @Override
            public Predicate toPredicate(Root<MedicalHistory> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                final Map<String, Field> fieldMap = ReflectUtil.getFieldMap(MedicalHistory.class);
                return cb.and(CommonUtils.pageSet(fieldMap,searchPage,cb,root));
            }
        };
        return this.thisRepository.findAll(specification, pageable);
    }
}
